package com.lkm.app_ui;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.m.Imple.fun.HoldNewSteelyardInfo;
import com.lkm.app_ui.m.Imple.initapp.MInitAppTask;
import com.lkm.app_ui.netapi.AppApi;
import com.lkm.app_ui.ui.DelegateInitFragment;
import com.lkm.app_ui.ui.fj.FjApp;
import com.lkm.app_ui.ui.fj.FjOrderFragment;
import com.lkm.app_ui.ui.fj.to.FjOrderTo;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.frame.module.ModuleManager;
import com.lkm.frame.task2.ITaskExecutor;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.task2.TaskManager;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.TaskIdIndex;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.netapi.Api;
import com.lkm.market2_0.task.DefaultTaskExecutor;
import com.mj.hx.yl.push.OnReceiverPushListener;
import com.mj.hx.yl.push.PushHandle;
import com.mj.hx.yl.push.PushHandleList;
import com.mj.hx.yl.push.PushManage;
import com.mj.hx.yl.push.PushReceiver;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

public class Market2_0ConfigeImpl extends ExpandConfig {

    public String interceptNetApi(String taskId) {
        if (taskId.equals(TaskIdIndex.LoadAppInitForSTask)) {
            return "{\"res\": 1,\"msg\": \"\",\"data\": []}";
        }
        return null;
    }

    @Override
    public Float price() {
        return RunTimeData.price;
    }

    @Override
    public String goodsName() {
        return RunTimeData.goodsName;
    }

    @Override
    public int interceptKeyCode(int keyCode) {

        if (keyCode == OnSteelyardKeyEvent.KEYCODE_VipW) {
            if (FjApp.install.isEnable()) {
                return OnSteelyardKeyEvent.KEYCODE_FJ;
            }
        }

        if (keyCode == OnSteelyardKeyEvent.KEYCODE_VipCard) {
            if (FjApp.install.isEnable()) {
                return OnSteelyardKeyEvent.KEYCODE_Fjswitch;
            }
        }


        return super.interceptKeyCode(keyCode);
    }

    @Override
    public String instask(String taskId, ResponEntity re, String json) {

        if (taskId.startsWith(TaskIdIndex.LoadSteelyardInfoTaskPre)) {
            HoldNewSteelyardInfo.isLoadFormNet(re.isSuccess());
        }

        if (re.isSuccess()) {

            MyApplication.getInstance().getSharedPreferences("netCache", Context.MODE_PRIVATE).edit().putString(taskId, json).apply();
        } else {

            return MyApplication.getInstance().getSharedPreferences("netCache", Context.MODE_PRIVATE).getString(taskId, null);

        }
        return null;
    }

    @Override
    public String getUIast_oid() {

        String oid = RunTimeData.steelyardInfo == null ? "" : "" + RunTimeData.steelyardInfo.getOrg();

        return oid;
    }

    @Override
    public boolean isUI() {
        return true;
    }

    @Override
    public String getServerApiHost() {
        String s = MyApplication.getInstance().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("tv_url", "http://zhongzi.web.ic1986.com/api/tc.ashx");
        //String s=MyApplication.getInstance().getSharedPreferences("settingapp",Context.MODE_PRIVATE).getString("tv_url", "http://192.168.1.126:9505/v2/index");
        return s;
    }

    @Override
    public InputStream getHttpsCertificates() {
        try {
            return MyApplication.getInstance().getResources().getAssets().open("astracedev.crt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int steelyardServerPort() {
        return 47111;
    }


//        return MyApplication.getInstance().isDebug();


    @Override
    public boolean isTest() {
        return true;
    }

    @Override
    public void saveValue(String key, String value) {
        MyApplication.getInstance().getSharedPreferences("privateConfige", Context.MODE_PRIVATE).edit().putString(key, value).apply();
    }

    @Override
    public String loadValue(String key, String default_) {
        return MyApplication.getInstance().getSharedPreferences("privateConfige", Context.MODE_PRIVATE).getString(key, default_);
    }

    @Override
    public void showLogInUI(final String log) {

//            MainActivity.mainActivity.runOnUiThread(new Runnable() {


//                        MainActivity.tv_logs.setText(log);


    }

    @Override
    public TaskManager getTaskManager2() {
        return MyApplication.getInstance().getTaskManager2();
    }

    @Override
    public ModuleManager getModuleManager() {
        return MyApplication.getInstance().getModuleManager();
    }

    @Override
    public void receiverPushContent(String customContent) {
        receiverContent(AppConst.getApplication(), customContent);
    }

    @Override
    public void acquireWakeLock(int timeout) {
        MyApplication.getInstance().acquireWakeLock(timeout);
    }

    @Override
    public void releaseWakeLock() {
        MyApplication.getInstance().releaseWakeLock();
    }

    @Override
    public Executor getTaskExecutor() {
        return com.lkm.comlib.Config.getTaskExecutor();
    }

    @Override
    public String getOrderTempFileDir() {

        return AppConfig.DataFile.orderTempFile;
    }

    public void inServerSteelyardMac(String serverSteelyardMac, String serverSteelyardMac_no) {
        this.serverSteelyardMac = serverSteelyardMac;
        this.serverSteelyardMac_no = serverSteelyardMac_no;
    }

    private String serverSteelyardMac = null;

    private String serverSteelyardMac_no = null;

    @Override
    public String getServerSteelyardMac(String steelyardNumno, String srcSteelyardMac) {


        if (!StringHelp.equals(steelyardNumno, serverSteelyardMac_no)) {
            serverSteelyardMac = null;
            serverSteelyardMac_no = null;
        }
        if (!StringHelp.isEmpty(serverSteelyardMac)) return serverSteelyardMac;


        if (!Api.isASTApi()) {

//            RunTimeData.LoaclSteelyardMac = AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("steelyardMac", "");
            return srcSteelyardMac;
        }


        if (AppConst.getTaskManager2() == null) return null;

        if (AppConst.getTaskManager2().getRunTask(getHoldSteelyardMacTaskId()) != null) {
            return null;
        }

        Task task = new HoldSteelyardMacTask(srcSteelyardMac);
        task.action();
        task.setParam(steelyardNumno);
        task.execTask();

        if (DelegateInitFragment.initFragment != null) {
            DelegateInitFragment.initFragment.reState();
        }
        return null;
    }

    public static String getHoldSteelyardMacTaskId() {
        return HoldSteelyardMacTask.class.getName();
    }

    private class HoldSteelyardMacTask extends TaskAdapter<String, Void, String> {


        private String srcSteelyardMac;

        public HoldSteelyardMacTask(String srcSteelyardMac) {
            super(new DefaultTaskExecutor(true), getHoldSteelyardMacTaskId(), AppConst.getTaskManager2());
            this.srcSteelyardMac = srcSteelyardMac;
        }

        @Override
        public void doExecuting(String param) {
            super.doExecuting(param);
            if (getIsContinue())
                load();
        }


        private int netBadCount = 0;

        private void load() {
            mTaskExecutor.executor(new Runnable() {
                @Override
                public void run() {
                    String steelyardNumno = getParam();
                    String steelyardMac   = "";


                    if ("4294967295".equals(steelyardNumno)) {

                        steelyardMac = AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("steelyardMac", "");
                    }

                    if (StringHelp.isEmpty(steelyardMac)) {
                        ResponEntity<String> re = getStringResponEntity(steelyardNumno);
                        if (re.isSuccess()) {
                            netBadCount = 0;
                            steelyardMac = re.getData();
                        } else {
                            AppUIHelp.tryShowTipsSHORT("芯片码加载失败，" + re.getMsg());
                            steelyardMac = null;
                        }
                    }

                    if (netBadCount >= 3 && StringHelp.isEmpty(steelyardMac)) {
                        steelyardMac = AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).getString("steelyardMac", "");

                        if (!StringHelp.isEmpty(steelyardMac)) {

                            if (!(srcSteelyardMac.contains("00000000") ||
                                    srcSteelyardMac.contains("ffffffff") || srcSteelyardMac.contains("4294967295"))) {
                                steelyardMac = srcSteelyardMac;
                            }
                        }
                    }

                    if (StringHelp.isEmpty(steelyardMac)) {
                        mTaskExecutor.post(() -> load(), 6 * 1000);
                    } else {
                        synchronized (this) {
                            RunTimeData.LoaclSteelyardMac = serverSteelyardMac = steelyardMac;
                            serverSteelyardMac_no = steelyardNumno;
                        }
                        AppConst.getApplication().getSharedPreferences("settingapp", Context.MODE_PRIVATE).edit().putString("serverSteelyardMac", serverSteelyardMac).putString("serverSteelyardMac_no", steelyardNumno).commit();
                        complete(serverSteelyardMac);
                    }
                }


            });
        }

        private ResponEntity<String> getStringResponEntity(String steelyardNumno) {
            String               json = AppApi.serverSteelyardMac(steelyardNumno, HoldSteelyardMacTask.this);
            ResponEntity<String> re   = ResponEntity.fromJson(json, String.class, "");


            if (StringHelp.isEmpty(json)) {
                netBadCount++;
            }
            return re;
        }

        @Override
        public void onEnd(boolean isCancel, String s) {
            super.onEnd(isCancel, s);

            if (DelegateInitFragment.initFragment != null) {
                DelegateInitFragment.initFragment.reState();
            }
        }
    }

    public static void receiverContent(Context context, String customContent) {
        OnReceiverPushListener or = PushManage.onReceiverPushListener;

        if (or != null)
            if (or.onReceiverPush_TextMessage(customContent)) return;

        if (customContent != null && customContent.length() != 0) {
            System.out.println("=========push " + customContent);
            customContent = customContent.trim();
            try {
                if (customContent.startsWith("[")) {

                    JsonParser jp  = new JsonParser();
                    JsonArray  jas = (JsonArray) jp.parse(customContent);
                    for (int i = 0; i < jas.size(); i++) {
                        handle(context, (JsonObject) jas.get(i));
                    }

                } else {
                    JsonParser jp = new JsonParser();
                    JsonObject js = (JsonObject) jp.parse(customContent);
                    handle(context, js);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean handle(final Context context, JsonObject js) {

        // System.out.println("=========PushReceiverData   " + json);

        if (js == null)
            return false;
        try {
            int         type;
            JsonElement stateJe = js.get("t");
            if (stateJe != null) {
                type = stateJe.getAsInt();
            } else {

                return false;
            }
            // if(result.type<0||result.type>10)


            final PushHandle<Object> ph = PushHandleList.getPushHandle(type);


            if (ph == null)
                return false;

            Object datat = null;
            if (ph.getDataClass() == null) {
                datat = null;
            } else {
                JsonElement dataJe = js.get("d");
                if (dataJe == null)
                    return false;
                datat = new Gson().fromJson(dataJe, ph.getDataClass());
            }
            final Object data = datat;


            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    ph.handler(context, data);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }
}
